package com.dony.common.utils.file;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.dony.common.utils.StringUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sundw
 * @version 1.0.0
 * @description OssUtils
 * @since 2022/9/10 23:24
 */
@Component
public class QiniuUtils implements InitializingBean {

    @Value("${qiniu.ak}")
    private String ak;
    @Value("${qiniu.sk}")
    private String sk;
    @Value("${qiniu.bucket}")
    private String bucketName;
    @Value("${qiniu.endpoint}")
    private String endpoint;


    // uploadToken
    String uploadToken;
    //创建上传对象
    UploadManager uploadManager;


    @Override
    public void afterPropertiesSet() throws Exception {
        uploadToken = Auth.create(ak, sk).uploadToken(bucketName);
        Configuration cfg = new Configuration();
        uploadManager = new UploadManager(cfg);
    }


    /**
     * 上传文件
     *
     * @param fileName
     * @param file
     */
    public String uploadFile(String fileName, MultipartFile file) {
        //把文件转化为字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            BufferedImage bi = null;
            if (height > 900 || width > 900) {
                bi = Thumbnails.of(bufferedImage).size(900, 900).outputQuality(0.8f).asBufferedImage();
            }else{
                bi = Thumbnails.of(bufferedImage).scale(0.9f).outputQuality(0.9f).asBufferedImage();
            }
            ImageIO.write(bi, "jpg", bos);
            //System.err.println("原大小："+file.getSize()/1024 +"现在大小："+bos.size()/1024);
            byte[] uploadBytes = bos.toByteArray();
            // 获取当前日期，并将其作为文件夹名
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date currentDate = new Date();
            String currentDateFolder = dateFormat.format(currentDate);
            String suffix = StringUtils.substring(fileName, fileName.lastIndexOf("."), fileName.length());
            String key = currentDateFolder + "/" + RandomUtil.randomStringUpper(6) + suffix;
            //开始上传
            Response response = uploadManager.put(uploadBytes, key, uploadToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {

        }
    }

}
